package chen.web.search;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class Config {

	private File indexDirectory = null;
	private boolean create = false;
	private Analyzer analyzer = null;
	private IndexWriter indexWriter = null;
	
	public Config(File indexDirectory, boolean create){
		this.setIndexDirectory(indexDirectory);
		this.setCreate(create);
		if(!indexDirectory.isDirectory()){
			throw new IllegalArgumentException("索引目录不存在");
		}
	}
	
	protected Analyzer getAnalyzer(){
		if(analyzer == null){
			analyzer = new IKAnalyzer();
		}
		return analyzer;
	}
	
	public void setAnalyzer(Analyzer analyzer){
		this.analyzer = analyzer;
	}

	public void setCreate(boolean create) {
		this.create = create;
	}

	protected boolean isCreate() {
		return create;
	}

	public void setIndexDirectory(File indexDirectory) {
		this.indexDirectory = indexDirectory;
	}

	protected File getIndexDirectory() {
		return indexDirectory;
	}
	
	protected IndexWriter getIndexWriter(){
		if(indexWriter == null){
			try {
				indexWriter = new IndexWriter(FSDirectory.open(getIndexDirectory()), getAnalyzer(), isCreate(), IndexWriter.MaxFieldLength.LIMITED);
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (LockObtainFailedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return indexWriter;
	}
	
	public void setIndexWriter(IndexWriter indexWriter){
		this.indexWriter = indexWriter;
	}
	
}
